package ace.module.captcha.test.core.controller;

import ace.cmp.core.model.R;
import ace.cmp.json.api.JsonService;
import ace.module.captcha.test.core.controller.model.request.GenericRequest;
import ace.module.captcha.test.core.controller.model.request.MapParams;
import ace.module.captcha.test.core.controller.model.request.UsernameParams;
import com.fasterxml.jackson.core.type.TypeReference;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Caspar 客户端入口
 */
@AllArgsConstructor
@RestController
@Slf4j
public class GenericParamsTestController {
  public static final String GENERIC_PARAMS = "/generic_params";
  public static final String STRING_PARAMS = "/string_params";
  public static final String USERNAME_PARAMS = "/username_params";
  private final JsonService jsonService;

  @PostMapping(GENERIC_PARAMS)
  public R<Object> genericParams(@Valid @RequestBody GenericRequest<MapParams> request) {
    String paramsString = jsonService.toJson(request.getParams());
    UsernameParams usernameParams = jsonService.toObject(paramsString, UsernameParams.class);
    log.info("jsonService_genericParams", jsonService.toJson(usernameParams));
    return R.ok(request);
  }

  @PostMapping(STRING_PARAMS)
  public R<Object> genericParams(@Valid @RequestBody String request) {
    TypeReference<GenericRequest<UsernameParams>> typeReference =
        new TypeReference<GenericRequest<UsernameParams>>() {};
    GenericRequest<UsernameParams> usernameParams =
        jsonService.toObject(request, typeReference.getType());
    return R.ok(usernameParams);
  }

  @PostMapping(USERNAME_PARAMS)
  public R<Object> username_params(@Valid @RequestBody GenericRequest<UsernameParams> request) {
    return R.ok(request);
  }
}
